from rest_framework import serializers
from .models import Task, Module, Language, TaskUser

"""
这是一个查询任务的序列化器
"""


class ModuleSerializer(serializers.ModelSerializer):
    """查询模块的序列化器"""

    class Meta:
        model = Module
        fields = '__all__'


class LanguageSerializer(serializers.ModelSerializer):
    """查询语言的序列化器"""

    class Meta:
        model = Language
        fields = '__all__'


class TaskSerializer(serializers.ModelSerializer):
    """查询任务的序列化器"""

    module = ModuleSerializer()  # 关联的 Module
    language = LanguageSerializer()  # 关联的 Language
    status = serializers.SerializerMethodField()
    answer = serializers.SerializerMethodField()  # 新增的answer字段

    class Meta:
        model = Task
        fields = '__all__'

    def get_status(self, obj):
        taskuser_info = getattr(obj, 'user_taskuser_info', None)
        if taskuser_info:
            return taskuser_info[0].status
        return None

    def get_answer(self, obj):
        """
        从Task.prefetch_related('taskuser_set')里拿到当前用户的答案
        """
        taskuser_info = getattr(obj, 'user_taskuser_info', None)
        if taskuser_info:
            # user_taskuser_info 是个列表（Prefetch结果）
            return taskuser_info[0].answer
        return None


class TaskUserSerializer(serializers.ModelSerializer):
    """获取学生表数据"""
    class Meta:
        model = TaskUser
        fields = '__all__'



